package com.example.bysj.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bysj.common.Constants;
import com.example.bysj.common.Result;
import com.example.bysj.controller.dto.UserDTO;
import com.example.bysj.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import com.example.bysj.service.IUserService;
import com.example.bysj.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chuanyuzhou
 * @since 2022-04-21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    //登录接口
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        String username=userDTO.getUsername();
        String password = userDTO.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        UserDTO dto=userService.login(userDTO);
        return Result.success(dto);
    }

    //注册接口
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){//  @RequestBody主要用来接收前端传递给后端的json字符串中的数据的，json转成java
        String username=userDTO.getUsername();
        String password = userDTO.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.register(userDTO));
    }

    @PostMapping//进行新增和修改
    public Result save(@RequestBody User user){//  @RequestBody主要用来接收前端传递给后端的json字符串中的数据的，json转成java
        return Result.success(userService.saveOrUpdate(user));
    }

    @DeleteMapping("/{uid}")
    public Result delete(@PathVariable Integer uid) {
        return Result.success(userService.removeById(uid));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> uids){
        return Result.success(userService.removeBatchByIds(uids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    //根据id查询
    @GetMapping("/{uid}")
    public Result findOne(@PathVariable Integer uid) {
        return Result.success(userService.getById(uid));
    }

    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String password){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        if(!"".equals(username)){
            queryWrapper.like("username",username);
        }
        if(!"".equals(password)){
            queryWrapper.like("password",password);
        }
        queryWrapper.orderByDesc("uid");
        return Result.success(userService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查出所有的数据
        List<User> list =userService.list();
        //通过工具类创建writer在内存操作，写出到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("uid","警员编号");
        writer.addHeaderAlias("username","警员姓名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("createTime","创建时间");

        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out=response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }
    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream=file.getInputStream();
        ExcelReader reader=ExcelUtil.getReader(inputStream);
        List<User> list=reader.readAll(User.class);
        userService.saveBatch(list);
        return Result.success(true);
    }

}

